package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.device.domain.Cabinet;
import com.share.device.domain.CabinetSlot;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.CabinetSlotMapper;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.ICabinetSlotService;
import com.share.device.service.IPowerBankService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank>
        implements IPowerBankService {

    private static final Logger log = LoggerFactory.getLogger(PowerBankServiceImpl.class);

    @Autowired
    private PowerBankMapper powerBankMapper;

    @Autowired
    private CabinetSlotMapper cabinetSlotMapper;



    //分页查询
    @Override
    public List<PowerBank> selectListPowerBank(PowerBank powerBank) {
        return powerBankMapper.selectListPowerBank(powerBank);
    }

    //添加
    @Override
    public int savePowerBank(PowerBank powerBank) {
        //1 判断powerBankNo是否存在，如果存在不进行添加
        String powerBankNo = powerBank.getPowerBankNo();
        //封装条件
        LambdaQueryWrapper<PowerBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PowerBank::getPowerBankNo,powerBankNo);
        Long count = powerBankMapper.selectCount(wrapper);
        //判断
        if(count > 0) {//如果存在不进行添加
            throw new ServiceException("充电宝编号已经存在");
        }
        //不存在做添加
        int rows = powerBankMapper.insert(powerBank);
        return rows;
    }

    //修改
    @Override
    public int updatePowerBank(PowerBank powerBank) {
        //1 判断状态是0才进行修改
        Long id = powerBank.getId();
        PowerBank oldPowerBank = powerBankMapper.selectById(id);
        if(oldPowerBank != null && "0".equals(oldPowerBank.getStatus())) {

            int rows = powerBankMapper.updateById(powerBank);
            return rows;
        }
        return 0;
    }

    @Override
    public PowerBank getByPowerBankNo(String powerBankNo) {
        return powerBankMapper.selectOne(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBankNo));
    }

    @Override
    public Map<String,PowerBank> getPowerBankByCabinetId(Long cabinetId) {
        List<CabinetSlot> cabinetSlots = cabinetSlotMapper.selectList(new LambdaQueryWrapper<CabinetSlot>().eq(CabinetSlot::getCabinetId, cabinetId));
        Map<String,PowerBank> list = new LinkedHashMap<>();
        if(!CollectionUtils.isEmpty(cabinetSlots)) {
            for (CabinetSlot item : cabinetSlots) {
                Long powerBankId = item.getPowerBankId();
                if(powerBankId != null) {
                    PowerBank powerBanks = powerBankMapper.selectOne(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getId, powerBankId));
                    list.put(item.getSlotNo(),powerBanks);
                }
            }
        }
        return list;
    }

    @Override
    public boolean updateElectricity(String powerBankNo, Integer electricity) {
        try {
            // 根据充电宝编号查询充电宝
            PowerBank powerBank = getByPowerBankNo(powerBankNo);
            if (powerBank == null) {
                log.error("充电宝不存在: powerBankNo={}", powerBankNo);
                return false;
            }
            
            // 更新电量（转换为BigDecimal）
            powerBank.setElectricity(new BigDecimal(electricity));
            powerBank.setUpdateTime(new Date());
            
            // 保存更新
            int result = powerBankMapper.updateById(powerBank);
            
            log.info("更新充电宝电量成功: powerBankNo={}, electricity={}", powerBankNo, electricity);
            return result > 0;
        } catch (Exception e) {
            log.error("更新充电宝电量失败: powerBankNo={}, electricity={}", powerBankNo, electricity, e);
            return false;
        }
    }

    @Override
    public List<PowerBank> searchNoUseList(String keyword) {
        LambdaQueryWrapper<PowerBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(PowerBank::getPowerBankNo,keyword);
        wrapper.eq(PowerBank::getStatus,0);
        List<PowerBank> list = powerBankMapper.selectList(wrapper);
        return list;
    }
}
